/**
 * Created by zzy on 2017/9/10.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    ScrollView,
    Dimensions,
    RefreshControl,
    DeviceEventEmitter,
    StatusBar,
    Platform,
    Linking,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'
import Constant from '../../js/Contant'
import AddressTopView from '../../luojs/componentluo/addresstopview';
import ViewPager from '../../js/component/ViewPager';
import TicketPanel from '../componentluo/ticketpanel';
import loginStore from "../store/LoginStoreLuo";
import TiketList from './TicketList';
import NetRequestLuo from '../util/NetRequest'
import * as WeChat from 'react-native-wechat'
import ProductCellH from '../componentluo/ProductCellH'
import addressMgrStore from '../../js/store/AddrMgrStore'
import Toast from 'react-native-easy-toast'
import shoppingCartStore from '../store/ShoppingCartStore'
import SplashScreen from 'react-native-splash-screen'
import AndroidUpdateUtil from '../../js/common/AndroidUpdateUtil.android'
var {height, width} = Dimensions.get('window');
import {observer} from 'mobx-react/native'
import {observe} from "../../node_modules/mobx/lib/mobx";
import waterStationStore from '../store/WaterStationStore'
import Share from '../../js/component/ShareModal'
import ShareUtil from '../../js/common/ShareUtil'
import bannerStore from '../store/BannerStore'
import {observable, action, computed} from 'mobx'
import UpdateMadal from '../../luojs/componentluo/UpdateMadal'
@observer
export default class HomeLuo extends Component{
    static navigationOptions = {
        header: ()=>{
            return Platform.OS=='ios' ? <StatusBar/> : null
        }
    };
    @observable isRefreshing=false;
    @observable preference=[];
    @observable shopId=0;
    @observable clientUpdateUrl='';
    constructor(props){
        super(props);
    }

    render(){
        //const img = require('../../asserts/home/banner1.png');
        //const img_second = require('../../luoasserts/homeLuo/home_banner_second.png');
        return <View style={{flex:1}}>
            <Head callback={()=>{this.props.navigation.navigate('CityChooser')}} share={this._startShare.bind(this)}/>
            <ScrollView
            refreshControl={<RefreshControl
                refreshing={this.isRefreshing}
                onRefresh={this._onRefresh.bind(this)}
                tintColor={Constant.TEXT_COLOR_9}
            />}>
            <View>
                <TouchableOpacity
                    activeOpacity={0.9}
                    onPress={() => {
                        this.props.navigation.navigate('DeliveryAddress')
                    }}
                    style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        backgroundColor: Constant.GRAYBGCOLOR,
                        height: 50
                    }}>
                    <AddressTopView/>
                </TouchableOpacity>
            </View>
                {
                    bannerStore.bannerUrls.length==0?(null):
                        <ViewPager images={bannerStore.bannerUrls} click={(i)=>{
                            //if(i==0){this.props.navigation.navigate('Flagship')}
                            if(bannerStore.bannList[i].linkType=='shopEntityProduct'){
                                    this.props.navigation.navigate('ProductsDetailsLuo',{productItemId:bannerStore.bannList[i].msgContent[1].linkValue,shopId:bannerStore.bannList[i].msgContent[0].linkValue});
                            }else if(bannerStore.bannList[i].linkType=='shopWaterTicketProduct'){
                                this.props.navigation.navigate('TicketDetails',{productItemId:bannerStore.bannList[i].msgContent[1].linkValue,shopId:bannerStore.bannList[i].msgContent[0].linkValue});
                            }
                        }}/>
                }
            <HotSale {...this.props}/>
            <View style={{marginTop:10}}>
                <TicketPanel tiketClick={()=>{this.props.navigation.navigate('TiketList')}} foodClick={()=>{this.props.navigation.navigate('OtherFoodHotSale')}}/>
            </View>
            <Preference products={this.preference} callBack={()=>{}} navigate={this.props.navigation.navigate} shopId={this.shopId}
                        addToShoppingCart={this._addToShoppingCart.bind(this)}/>
        </ScrollView>
            <Toast ref="toast" position='bottom'/>
            <Share ref="modal1" shareCall={this._share.bind(this)} info={{}}/>
            <UpdateMadal ref="updateMadal" update={this.upDate.bind(this)} cancel={this.updateMadalClose.bind(this)}/>
        </View>
    }
    _startShare(){
        this.refs.modal1._open();
    };
    _share(type, shop) {
        var shareParam = {
            type: 'news',
            title: '汇贝-订水送水',
            description: '下载汇贝APP，桶装水、粮油生鲜极速配送！' ,
            messageAction: undefined,
            messageExt: undefined,
            webpageUrl: this.clientUpdateUrl,
        };
        type == 0 ? ShareUtil.shareToSession(shareParam) : ShareUtil.shareToTimeline(shareParam)
    }
    _addToShoppingCart(item){
        let param={
            productItemId: item.productItemModels[0].productItemId,
            productType: item.type,
            shopId: this.shopId,
        };
        NetRequestLuo.addShoppingCart(param,'increase').then((data)=>{
            LOG('加入购物车--------'+JSON.stringify(data));
            shoppingCartStore.getShoppingCart();
            DeviceEventEmitter.emit('refreshShopList');//刷新购物车
            this.refs.toast.show('已加入购物车');
        })
    }
    _onRefresh(){
        this.hotSale();
        bannerStore.getBanner();
    }
     componentWillMount(){
         //AndroidUpdateUtil._checkUpdate();
         WeChat.registerApp('wx9d8c5a909b2d9bcc');
        //检测是否登录
        this.fetch();
        observe(addressMgrStore, 'activeAddress', (change) => {//区域地址变化刷新
             waterStationStore.getShopList();
        });
     }

    async fetch(){
        let hasLogin =await loginStore.loginState() ;
        if (!hasLogin) {
            this.touristLogin();
        }else{
            this.hotSale();
        }
        bannerStore.getBanner();
    }
    componentDidMount() {
        setTimeout(() => {
            SplashScreen.hide();
        }, 2000);
        this.androidUpdate();
        // 监听登陆退出事件
        this.loginout = DeviceEventEmitter.addListener(Constant.LOGINOUT,this.touristLogin.bind(this));
        this.loginin = DeviceEventEmitter.addListener(Constant.LOGINOK,this.hotSale.bind(this));
    }
    androidUpdate(){
        let param={
            version:Constant.ANDROIDVERSIONCODE
        };
        NetRequestLuo.update(param).then((data)=>{
            LOG('版本信息----------'+JSON.stringify(data));
            if(data.needUpdate==true){
                this.updateMadalOpen(data.description);
            }
            this.clientUpdateUrl=data.clientUpdateUrl;
        })
    }
    updateMadalOpen(description){
        this.refs.updateMadal.openModal(description);
    }
    updateMadalClose(){
        this.refs.updateMadal.closeModal();
    }
    upDate(){
        Linking.openURL(this.clientUpdateUrl);
        this.updateMadalClose();
    }
    componentWillUnmount(){
        this.loginout.remove();
        this.loginin.remove();
    };
    async touristLogin(){
        let hasLogin =await loginStore.loginState() ;
        NetRequestLuo.loginTourist().then((data)=>{
            LOG('游客登录-------------'+JSON.stringify(data)+'       '+hasLogin);
                if (!hasLogin) {
                    loginStore.save('',data.access_token,data.access_secret);
                }else {
                    loginStore.update('',data.access_token,data.access_secret);
                }
        })

    }

    refreshData(){
        shoppingCartStore.getShoppingCart();
        DeviceEventEmitter.emit('refreshShopList');//刷新购物车
        addressMgrStore.refreshDeliveryList();
    }
    hotSale(){
        let guessParam={

       };
       NetRequestLuo.guessLike(guessParam).then((data)=>{
           LOG('猜你喜欢-------------'+JSON.stringify(data));
           if(data!=undefined){
              this.preference=data.productList;
              this.shopId=data.shopId
           }
           this.isRefreshing=false;
       });
        this.refreshData();
    }
}
@observer
class Head extends Component{
    render(){
        let {callback,share}=this.props;
        return <View style={[{flexDirection:'row',alignItems:'center',justifyContent:'center',backgroundColor:'white'},styles.headerStyle]}>
            <TouchableOpacity style={{position:'absolute',flexDirection:'row',left:10,alignItems:'center'}} onPress={callback} activeOpacity={0.9}>
                <Text>{addressMgrStore.mapAuto.city}</Text>
                <Icon name="ios-arrow-down" color="gray" size={14}/>
            </TouchableOpacity>
            <Text style={{color:'black',fontSize:18}}>订水</Text>
            <TouchableOpacity  style={{position:'absolute',right:10,alignItems:'center'}} activeOpacity={0.9} onPress={share}>
            <Image style={{width:25,height:25}} source={require('../../asserts/shop/common_head_icon_share.png')}></Image>
            </TouchableOpacity>

        </View>
    }
}
@observer
class HotSale extends Component{
    render(){
        return <View>
            <View style={{flexDirection:'row',justifyContent:'center',backgroundColor:'white',padding:5}}>
                <Text>桶装水热卖</Text>
            </View>
            {/*<Image*/}
                {/*style={{width:width,height:165}}*/}
                {/*source={require('../../luoasserts/homeLuo/home_banner.png')}/>*/}
            {
                bannerStore.bannerHotSaleUrls.length==0?(null):
                    <ViewPager images={bannerStore.bannerHotSaleUrls} click={(i)=>{
                        if(bannerStore.bannerHotSale[i].linkType=='shop'){
                            //this.props.navigation.navigate('HotSaleList',{shopId:bannerStore.bannerHotSale[i].linkData,title:bannerStore.bannerHotSale[i].title});
                            this.props.navigation.navigate('WaterStation',{shopId:bannerStore.bannerHotSale[0].msgContent[0].linkValue});
                        }
                    }}/>
            }
        </View>
    }
}
class Preference extends Component{
    render(){
        let {products,callBack,navigate,shopId,addToShoppingCart}=this.props;
        return <View>
            <View style={{flexDirection:'row',justifyContent:'center',backgroundColor:'white',padding:5,marginTop:10}}>
                <Text>猜你喜欢</Text>
            </View>
            <View style={{flexDirection:'row',flexWrap:'wrap'}}>
            {
                products.map((item,i)=>{
                  return <ProductCellH key={i} item={item} addToShoppingCart={addToShoppingCart} callback={()=>{
                      navigate('ProductsDetailsLuo',{productItemId:item.productItemModels[0].productItemId,shopId:shopId});
                  }}/>
              })
            }
            </View>
        </View>
    }
}

const styles = {
    headerStyle:{
        paddingTop:Platform.OS=='ios' ? 30 : 15,
        paddingBottom:Platform.OS=='ios' ? 10 : 15
    }
}